package com.example.app.manager

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.view.View
import android.view.animation.LinearInterpolator
import com.blankj.utilcode.util.ScreenUtils
import com.blankj.utilcode.util.ViewUtils

/**
 * CreateBy:Joker
 * CreateTime:2024/9/11 20:03
 * description：banner移动播放器
 */
class CommonBannerPlayer {

    private var animatorSet: AnimatorSet? = null

    fun startPlay(bannerView: View, playResult: () -> Unit) {
        val sw = ScreenUtils.getScreenWidth().toFloat()
        val startX = if (ViewUtils.isLayoutRtl()) -sw else sw
        val endX = -startX

        bannerView.translationX = startX //初始位置
        bannerView.setLayerType(View.LAYER_TYPE_HARDWARE, null)

        val animators = listOf<ObjectAnimator>(
            //1、bannerView显示出来
            ObjectAnimator.ofFloat(bannerView, View.ALPHA, 0f, 1f).apply {
                duration = 1000L
                interpolator = LinearInterpolator()
            },

            //2、需要移动的view 移动进来
            ObjectAnimator.ofFloat(bannerView, View.TRANSLATION_X, startX, 0f).apply {
                duration = 2000L
                interpolator = LinearInterpolator()
            },

            //3、需要移动的view 移动出去
            ObjectAnimator.ofFloat(bannerView, View.TRANSLATION_X, 0f, endX).apply {
                startDelay = 2000L
                duration = 500L
                interpolator = LinearInterpolator()
            },

            //4、bannerView消失
            ObjectAnimator.ofFloat(bannerView, View.ALPHA, 1f, 0f).apply {
                duration = 500L
                interpolator = LinearInterpolator()
            }
        )

        animatorSet = AnimatorSet().apply {
            playSequentially(animators)
            start()
            addListener(object : AnimatorListenerAdapter() {
                override fun onAnimationEnd(animation: Animator) {
                    super.onAnimationEnd(animation)
                    playResult.invoke()
                }
            })
        }
    }

    fun stopPlay() {
        animatorSet?.apply {
            removeAllListeners()
            cancel()
        }
        animatorSet = null
    }

    fun isPlaying(): Boolean {
        return animatorSet?.isRunning == true
    }
}